<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input
          v-model="query.taskName"
          size="small"
          clearable
          placeholder="请输入任务名称"
          class="filter-item"
          style="width: 200px;"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.transferStatus"
          size="small"
          class="filter-item"
          placeholder="请选择迁移状态"
          filterable
          clearable
          style="width:200px"
        >
          <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <el-table
      ref="table"
      :data="crud.data"
      style="width: 100%;"
      @selection-change="crud.selectionChangeHandler"
      @filter-change="crud.handleFilterChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column v-if="columns.visible('taskName')" :show-overflow-tooltip="true" prop="taskName" label="任务名称" min-width="150" />
      <el-table-column v-if="columns.visible('migrationType')" :show-overflow-tooltip="true" prop="migrationType" label="迁移类型" min-width="150" />
      <el-table-column v-if="columns.visible('transferStatus')" label="迁移状态" prop="transferStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.transferStatus === 'TODO'" type="info">待迁移</el-tag>
          <el-tag v-if="scope.row.transferStatus === 'PROCESSING'">迁移中</el-tag>
          <el-tag v-if="scope.row.transferStatus === 'FINISH'" type="success">完成</el-tag>
          <el-tag v-if="scope.row.transferStatus === 'FAIL'" type="danger">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('transferSuccessCount')" prop="transferSuccessCount" label="建表进度" min-width="280">
        <template slot-scope="scope">
          <el-tag type="info">总数: {{ scope.row.transferTotal }}</el-tag>
          <el-tag type="success" style="margin: 0 5px">迁移成功: {{ scope.row.transferSuccessCount }}</el-tag>
          <el-tag type="danger">迁移失败: {{ scope.row.transferFailCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('startTime')" prop="startTime" label="开始时间" min-width="150">
        <template slot-scope="scope">
          <div>
            <i class="el-icon-time" />
            <span style="margin-left: 5px">{{ scope.row.startTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('endTime')" prop="endTime" label="结束时间" min-width="150">
        <template slot-scope="scope">
          <div>
            <i class="el-icon-time" />
            <span style="margin-left: 5px">{{ scope.row.endTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('upUserName')" prop="upUserName" label="更新人" />
      <el-table-column v-if="columns.visible('upTs')" prop="upTs" label="更新时间" min-width="150" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="toDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination />
    <!--新增/编辑弹窗-->
    <el-dialog
      v-if="crud.status.cu === 1"
      :visible.sync="crud.status.cu === 1"
      append-to-body
      :close-on-click-modal="false"
      title="表迁移"
      top="5vh"
      width="1200px"
      @close="crud.cancelCU()"
    >
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="130px">
        <el-row>
          <el-col :span="22">
            <el-steps :active="active" finish-status="success" simple>
              <el-step title="基本信息" />
              <el-step title="迁移结果" />
            </el-steps>
          </el-col>
          <el-col :span="2">
            <div class="grid-content bg-purple-light">
              <el-button icon="el-icon-question" class="assist" @click="helpFormVisible = true">帮助</el-button>
            </div>
          </el-col>
        </el-row>
        <div v-if="active === 0">
          <create-task v-if="active === 0" :key="0" ref="createTask" :form="form" :task-pk-id="form.pkId" />
          <div slot="footer" class="dialog-footer" style="width:100%;text-align: center;margin-top: 10px">
            <el-button @click="crud.cancelCU()">关 闭</el-button>
            <el-button type="warning" :class="{btnDisabled: form.isHiddenValu}" @click="saveButNoCreate()">保存但不建表</el-button>
            <el-button type="primary" @click="toConvert">下一步(建表)</el-button>
          </div>
        </div>
        <div v-if="active === 1">
          <create-task v-if="active === 1" :key="1" ref="transferResult" :form="form" :task-pk-id="form.pkId" :details-flag="detailsFlag" />
          <div class="dialog-footer" style="width:100%;text-align: center;margin-top: 40px">
            <el-button type="primary" @click="back">上一步</el-button>
            <el-button type="primary" @click="crud.cancelCU()">关闭</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
    <!-- 查看帮助文档 -->
    <el-dialog title="帮助" :visible.sync="helpFormVisible" width="1200px">
      <div>
        <table-transfer-helper />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tableTransferTask from '@/api/data/table/tableTransferTask'
import validateTaskName from '@/utils/taskNameRepeat'
import tableTransferList from '@/api/data/table/tableTransferList'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation.vue'
import pagination from '@crud/Pagination'
import createTask from './components/create-task/create-task.vue'
import tableTransferHelper from './components/helper/helper.vue'

const defaultCrud = CRUD({
  title: '表迁移任务',
  url: '/api/data/table/task',
  crudMethod: { ...tableTransferTask }
})
const defaultForm = {
  pkId: '',
  taskName: null,
  migrationType: '',
  transferMethod: '0',
  needPartition: '1',
  sourceConnPkId: '',
  targetConnPkId: '',
  sourceDbName: '',
  sourceTableName: '',
  targetDbName: '',
  targetTableName: '',
  tableTransferList: [],
  partitionFieldName: '',
  transferStatus: 'TODO',
  isHiddenValu: false
}

export default {
  // eslint-disable-next-line vue/no-unused-components
  components: { tableTransferHelper, createTask, crudOperation, rrOperation, pagination },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      permission: {
        add: ['admin', 'tableTransfer:add'],
        edit: ['admin', 'tableTransfer:edit'],
        del: ['admin', 'tableTransfer:del']
      },
      statusOptions: [
        { key: 'TODO', label: '待迁移' },
        { key: 'PROCESSING', label: '迁移中' },
        { key: 'FINISH', label: '完成' },
        { key: 'FAIL', label: '失败' }
      ],
      detailsFlag: false,
      taskPkId: '',
      active: 0,
      helpFormVisible: false,
      rules: {
        taskName: [
          { required: true, validator: validateTaskName.bind(this, tableTransferTask, this.form), trigger: 'blur' }
        ],
        transferMethod: [
          { required: true, message: '请选择覆盖类型', trigger: 'change' }
        ],
        sourceConnPkId: [
          { required: true, message: '请选择源数据源类型', trigger: 'change' }
        ],
        targetConnPkId: [
          { required: true, message: '请选择目标数据源类型', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.crud.resetQuery(false)
  },
  methods: {
    [CRUD.HOOK.beforeToAdd](crud) {
      this.form = crud.form
      this.detailsFlag = false
      this.taskPkId = ''
      this.active = 0
    },
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.form = crud.form
      if (this.form.transferStatus === 'TODO') {
        this.detailsFlag = false
        this.form.isHiddenValu = false
        this.active = 0
      } else {
        this.detailsFlag = true
        this.form.isHiddenValu = true
        this.active = 1
      }
      // 用于编辑功能时获取任务名称
      this.form.validateName = this.form.taskName
      this.taskPkId = form.pkId
      const param = {
        'taskPkId': form.pkId
      }
      tableTransferList.findListByPage(param).then(data => {
        this.form.tableTransferList = data.content
      })
    },
    checkHasTableList() {
      if (this.crud.form.tableTransferList.length < 1) {
        this.$notify({ title: '告警', message: '请选择上传或选择要迁移的表！', type: 'warning' })
        return false
      } else {
        if (this.$refs['createTask'].isDbShow.find(database => database) || this.$refs['createTask'].isShow.find(table => table)) {
          this.$notify({ title: '告警', message: '请保存当前修改', type: 'warning' })
          return false
        }
      }
      return true
    },
    // 保存但不执行建表操作
    saveButNoCreate() {
      if (!this.form.isHiddenValu) {
        this.$refs['form'].validate((valid) => {
          if (valid && this.checkHasTableList()) {
            if (this.form.pkId != null) {
              tableTransferTask.edit(this.form).then(rsp => {
                this.crud.notify(rsp, CRUD.NOTIFICATION_TYPE.SUCCESS)
                this.cancelCU()
                this.crud.refresh()
              }).catch(err => {
                console.log(err)
              })
            } else {
              this.cancelCU()
            }
          }
        })
      }
    },
    // 保存并建表并跳转至新增第二步操作
    toConvert() {
      if (this.detailsFlag) {
        this.active++
      } else if (!this.form.isHiddenValu) {
        this.$refs['form'].validate((valid) => {
          if (valid && this.checkHasTableList()) {
            const param = { taskPkId: this.form.pkId }
            tableTransferList.findListByPage(param).then(data => {
              if (data.content.length !== 0 && data.content[data.content.length - 1].targetCreateSql !== null) {
                tableTransferTask.edit(this.form).then(rsp => {
                  tableTransferTask.createTable(this.form.pkId).then(() => this.crud.refresh())
                  this.form.isHiddenValu = true
                  this.detailsFlag = true
                  this.active++
                }).catch(err => {
                  console.log(err)
                })
              } else {
                this.crud.notify('请选择要迁移的表并等待SQL语句生成！', CRUD.NOTIFICATION_TYPE.WARNING)
              }
            })
          } else {
            return false
          }
        })
      } else {
        this.detailsFlag = true
        this.active++
      }
    },
    back() {
      this.form.isHiddenValu = true
      this.active--
    },
    // 查看建表任务详情
    toDetail(row) {
      this.form = row
      this.form.isHiddenValu = true
      this.detailsFlag = true
      const param = {
        'taskPkId': row.pkId
      }
      tableTransferList.findListByPage(param).then(data => {
        this.form.tableTransferList = data.content
        this.active = 1
        if (this.form.transferStatus === 'TODO') {
          this.active = 0
        }
        this.crud.status.edit = 1
      })
    },
    // 取消操作
    cancelCU() {
      this.crud.cancelCU()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.assist {
  min-height: 46px;
  color: #fff;
  background-color: #ff4949;
  border-color: #ff4949;
}
.btnDisabled{
  color: #FFF;
  cursor: not-allowed;
  background-color: #f3d19e;
  border-color: #f3d19e;
}
</style>
